import operator
import os

from qutebrowser.api import interceptor, message

list_from = []
list_to = []
env_from = os.getenv("WEB_REDIRECT_FROM")
env_to = os.getenv("WEB_REDIRECT_TO")

if env_from is not None and env_from != "":
    list_from = env_from.split()
else:
    message.error("Environment variable WEB_REDIRECT_FROM is undefined or empty")


if env_to is not None and env_to != "":
    list_to = env_to.split()
else:
    message.error("Environment variable WEB_REDIRECT_TO is undefined or empty")

if len(list_from) != len(list_to):
    message.warning("WEB_REDIRECT_FROM and WEB_REDIRECT_TO are not the same lenght!")

REDIRECT_MAP = {}

for i in range(min(len(list_from), len(list_to))):
    REDIRECT_MAP[list_from[i]] = operator.methodcaller('setHost', list_to[i])


def int_fn(info: interceptor.Request):
    if (info.resource_type != interceptor.ResourceType.main_frame or info.request_url.scheme() in {"data", "blob"}):
        return
    url = info.request_url
    host = url.host()
    redir = REDIRECT_MAP.get(host)
    if redir is not None and redir(url) is not False:
        message.info("Redirecting from " + host + " to " + url.host())
        info.redirect(url)


interceptor.register(int_fn)
